//
//  GTListLoader.m
//  WKWebViewStudy
//
//  Created by Jason Len on 2019/9/17.
//  Copyright © 2019年 Jason. All rights reserved.
//

#import "GTListLoader.h"
#import <AFNetworking.h>
#import "GTListItem.h"

@implementation GTListLoader


// 3.实现带回调函数(Block)的网络请求
-(void)loadListDataWithFinishBlock:(GTListLoaderFinishBlock)finishBlock{
    NSString *urlString= @"http://v.juhe.cn/toutiao/index?type=top&key=97ad001bfcc2082e2eeaf798bad3d54e";
    NSURL *url = [NSURL URLWithString:urlString];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSession * session = [NSURLSession sharedSession];
    //实现简单请求
//    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    //实现带回调的请求
    NSURLSessionDataTask *dataTask=[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSError *jsonError;
        id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
        
#warning 类型检查
        __unused NSArray *dataArray = [((NSDictionary *) [((NSDictionary *)jsonObj) objectForKey:@"result"])objectForKey:@"data"];
        NSMutableArray *listItemArray = @[].mutableCopy;
        for(NSDictionary *info in dataArray){
            GTListItem *listItem = [[GTListItem alloc]init];
            [listItem configWithDictionary:info];
            [listItemArray addObject:listItem];
        }
        
        //4.更新主线程UI 所以使用dispatch_async
        dispatch_async(dispatch_get_main_queue(), ^{
            //5.回调 finishBlock
            if(finishBlock){
                finishBlock(error==nil,listItemArray);
            }
        });
        
    }];	
    
    [dataTask resume];
    
}
//使用AFNetworking 实现请求
-(void)loadListData1{
    NSString *urlString = @"http://v.juhe.cn/toutiao/index?type=top&key=97ad001bfcc2082e2eeaf798bad3d54e";
    NSURL *url=[NSURL URLWithString:urlString];
    [[AFHTTPSessionManager manager]GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

@end
